/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package JavaClass;

import DAO.AccountDAO;
import DAO.DetailedLessonDAO;
import DAO.LessonListDAO;
import DAO.OptionDAO;
import DTO.AccountDTO;
import generate.DetailedLesson.DetailedLesson;
import generate.DetailedLesson.DetailedLessons;
import generate.lessonList.LessonLists;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.xml.xpath.XPathConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 *
 * @author dienvm60347
 */
public class ControllerServlet extends HttpServlet {

    private String home = "homepage.jsp";
    private String register = "register.jsp";
    private String getinfo = "getinfo.jsp";

    private String detailType_AddTab = "";
    private int lessonId_AddTab = 0;
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            String username = request.getParameter("txtUsername");
            String password = request.getParameter("txtPassword");
            String currentPage = request.getParameter("currentPage");
            //<editor-fold desc="Login">
            if(action.equals("Đăng nhập")){
                String url = currentPage;
                String role = AccountDAO.checkLogin(username, password);
                if(role !=null){
                    url = currentPage;
                    HttpSession session = request.getSession();
                    session.setAttribute("USERNAME", username);
                    session.setAttribute("ACCOUNT", role);
                } else{
                    request.setAttribute("invalid", "true");
                }
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            }
            //</editor-fold>
            //<editor-fold desc="Exit">
            else if(action.equals("Thoát")){
                HttpSession session = request.getSession();
                session.removeAttribute("USERNAME");
                session.invalidate();
                RequestDispatcher rd = request.getRequestDispatcher(home);
                rd.forward(request, response);
            }
            //</editor-fold>
            //<editor-fold desc="Get menu">
            else if(action.equals("regis")){
                String url = register;
                List<AccountDTO> list = new ArrayList();
                list = AccountDAO.getAllUser();
                if(list.size()>0){
                    request.setAttribute("LIST", list);
                }
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            }
            //</editor-fold>
            //<editor-fold desc="Register">
            else if(action.equals("Đăng ký")){
                String user = request.getParameter("txtUser");
                String pass = request.getParameter("txtPass");
                String fullname = request.getParameter("txtFull");
                String email = request.getParameter("txtEmail");
                String birth = request.getParameter("ddlDay") + "/"
                        + request.getParameter("ddlMonth") + "/"
                        + request.getParameter("ddlYear");
                String sex = request.getParameter("sex");
                String address = request.getParameter("txtAdd");
                String phone = request.getParameter("txtPhone");
                boolean result = AccountDAO.regisAccount(user, pass, fullname, email, birth, sex, address, phone);
                String url = register;
                if(result){
                    url = url+"?result=success";
                }
                response.sendRedirect(url);
            }
            //</editor-fold>
            //<editor-fold desc="Get lesson list">
            else if (action.equals("lessonList")){
                String optionId = request.getParameter("optionId");
                String optionType = request.getParameter("optionType");

                LessonListDAO lesson = new LessonListDAO();
                LessonLists list = new LessonLists(lesson.getListLessonByOptionId(optionId));
                JaxBFunction.marshall(getServletContext().getRealPath("/")
                        + "xml/getLessonListByOptionId.xml", list);
                Thread.sleep(1000);

                String url = "LessonList.jsp?ID=" + optionId + "&TYPE=" + optionType;
                response.sendRedirect(url);
            }
            //</editor-fold>
            //<editor-fold desc="Lesson detail">
                else if(action.equals("ldetail")){
//                int lessonId = Integer.parseInt(request.getParameter("lessonId"));
//                String detailType = null;
                    lessonId_AddTab = 0;
                    detailType_AddTab = null;

                    lessonId_AddTab = Integer.parseInt(request.getParameter("lessonId"));
                String url = null;
                if(request.getParameter("detailType") !=null){
                    detailType_AddTab = request.getParameter("detailType");
                }
                //tao file xml
                DetailedLessonDAO dlessonDAO = new DetailedLessonDAO();
                DetailedLessons detaillessons = new DetailedLessons();
                List<DetailedLesson> dlessons = dlessonDAO.getDLessonByID(lessonId_AddTab,detailType_AddTab);
                for(int i = 0; i< dlessons.size(); i++){
                    detaillessons.getDetailedLesson().add(dlessons.get(i));
                }
                JaxBFunction.marshall(getServletContext().getRealPath("/") + "xml/DetailedLessons.xml", detaillessons);
                
                if(detailType_AddTab==null){
                    url = "DetailedLesson.jsp?lessonId=" + lessonId_AddTab;
                }else{
                    url = "DetailedLesson.jsp?lessonId=" + lessonId_AddTab + "&detailType=" + detailType_AddTab;
                }
//                RequestDispatcher rd = request.getRequestDispatcher(url);
//                rd.forward(request, response);
                 response.sendRedirect(url);
                }

            //</editor-fold>
            //<editor-fold desc="get menu">
            else if(action.equals("getMenu")){ 
                List listOption = new ArrayList();
                listOption = OptionDAO.getOption();
                String url = home;
                if(listOption!=null){
                    HttpSession session = request.getSession();
                    session.setAttribute("MENU", listOption);
                }
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            }
            //</editor-fold>
            //<editor-fold desc="get information">
            else if(action.equals("Gửi thông tin")){ //
                String user =  request.getParameter("txtUser");
                String email = request.getParameter("txtMail");
                String url = getinfo;
                String newpass = AccountDAO.checkUserEmail(user, email);
                if(newpass!=null){
                    request.setAttribute("PASS", newpass);
                    AccountDAO.updatePass(newpass, user);
                } else{
                    url +="?found=not";
                }
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            }
            //</editor-fold>
            //<editor-fold desc=" get lesson list for admin">
            else if(action.equals("lessonListAdmin")){ 
                String optionid = request.getParameter("optionId");
                String optiontype = request.getParameter("optionType");
                String valid = request.getParameter("validate");
                List lessonlist = new ArrayList();
                String path = getServletContext().getRealPath("/")+ "xml/LessonListsAdmin.xml";
                String url = "lessonlist_admin.jsp";

                LessonListSAXProcessor lsp = new LessonListSAXProcessor();
                lessonlist = lsp.save(path, optionid);

                request.setAttribute("VALID", valid);
                request.setAttribute("LISTLESSON", lessonlist);
                request.setAttribute("TYPE", optiontype);
                request.setAttribute("ID", optionid);
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            }
            //</editor-fold>
            //<editor-fold desc="Update lessonlist">
            else if(action.equals("Cập nhật"))
            {
                String lessonName = request.getParameter("txtLessonName");
                String lessonid = request.getParameter("txtLessonID");
                String optionType = request.getParameter("txtType");
                String optionid = request.getParameter("txtOptionID");
                String validate = null;
                String path = getServletContext().getRealPath("/")+ "xml/LessonListsAdmin.xml";
                String contentpath =  getServletContext().getRealPath("/");
                String xsdpath = contentpath.substring(0, contentpath.length()-11) + "/src/java/Schema/lessonList.xsd";
                Document doc = DOMParser.parseDom(path);
                String xpath = "//*[local-name()='lessonList'][*[local-name()='lessonId']]"
                        + "[" + lessonid +"]/*[local-name()='lessonName']";
                Node result = (Node) DOMParser.excuteXPath(doc, xpath, XPathConstants.NODE);
                if(result!=null){
                    result.setTextContent(lessonName);
                    DOMParser.transfromDom(path, doc);
                    boolean valid = SchemaValidation.validateXMLSchema(xsdpath, path);
                    if(!valid){
                        LessonListDAO lesson = new LessonListDAO();
                        LessonLists list = new LessonLists(lesson.getAllLesson());
                        JaxBFunction.marshall(path, list);
                        validate = "false";
                    } else {
                        LessonListDAO.updateLessonNameByID(lessonid, lessonName);
                    }
                }
                String url = "ControllerServlet?optionId="+ optionid 
                        + "&optionType=" + optionType + "&action=lessonListAdmin&validate="+validate;
                response.sendRedirect(url);
            }
            //</editor-fold>
            //<editor-fold desc="Delete Lesson">
//            else if(action.equals("Xóa")){
//                String lessonid = request.getParameter("txtLessonID");
//                String optionType = request.getParameter("txtType");
//                String optionid = request.getParameter("txtOptionID");
//                String path = getServletContext().getRealPath("/")+ "xml/LessonListsAdmin.xml";
//
//                Document doc = DOMParser.parseDom(path);
//
//                String Xpath = "//*[local-name()='lessonList'][*[local-name()='lessonId']]"
//                        + "[" + lessonid +"]";
//                Node result = (Node) DOMParser.excuteXPath(doc, Xpath, XPathConstants.NODE);
//                if(result !=null){
//                    Node parent = result.getParentNode();
//                    parent.removeChild(result);
//                    DOMParser.transfromDom(path, doc);
//                }
//                String url = "ControllerServlet?optionId="+ optionid
//                        + "&optionType=" + optionType + "&action=lessonListAdmin";
//                response.sendRedirect(url);
//            }
            //</editor-fold>
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally {
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
         boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	        if (isMultipart) {
                        String url = null;
                        String tabname = null;
                        String filelocation = null;
	        	// Create a factory for disk-based file items
	        	FileItemFactory factory = new DiskFileItemFactory();
	        	// Create a new file upload handler
	        	ServletFileUpload upload = new ServletFileUpload(factory);
	            try {
	            	// Parse the request
	            	List /* FileItem */ items = upload.parseRequest(request);
	                Iterator iterator = items.iterator();
	                while (iterator.hasNext()) {
	                    FileItem item = (FileItem) iterator.next();
	                    if (item.isFormField()) {
	                         String fieldname = item.getFieldName();
                                String fieldvalue = item.getString("UTF-8");
                                if (fieldname.equals("txtNewTabName")) {
                                    tabname = fieldvalue;
                                }
	                    }else{
                                String fileName = item.getName();
	                        File path = new File("D:/Data");
	                        if (!path.exists()) {
	                            path.mkdirs();
	                        }
	                        File uploadedFile = new File(path + "/" + tabname +"_" + fileName);
                                filelocation = uploadedFile.getPath();
	                        item.write(uploadedFile);
                            }                          
	                }
                            DetailedLessonDAO.insertDLesson(lessonId_AddTab, tabname, filelocation, detailType_AddTab);
                         //set String url
                              if(detailType_AddTab!=null){
                                  url = "ControllerServlet?action=ldetail&lessonId=" + lessonId_AddTab + "&detailType="+detailType_AddTab;
                              }else{
                                     url = "ControllerServlet?action=ldetail&lessonId=" + lessonId_AddTab;
                              }
                                response.sendRedirect(url);
	            } catch (FileUploadException e) {
	                e.printStackTrace();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }else{
                 processRequest(request, response);
                }       
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
